<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="form.sp_id ? '编辑' : '添加'" v-model="visible" align-center width="65%" :z-index="2000"
    @close="handleClose">
    <el-form ref="formRef" :model="form" label-position="top" :label-width="140">
      <div class="grid grid-cols-7 gap-x-3">
        <el-form-item label="账期名称" prop="name" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]" class="col-span-6">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="2" active-text="启用" inactive-text="禁用"
          inline-prompt />
        </el-form-item>
      </div>
      <el-form-item label="配置类型" prop="bank_type">
        <el-radio-group v-model="form.config_type" @change="typeChange">
          <el-radio :value="1">单类型配置</el-radio>
          <el-radio :value="2">多类型混合配置</el-radio>
        </el-radio-group>
      </el-form-item>
      <div class="mt-[8px]" :class="form.config_type !== 1?' px-[8px] py-[8px] rounded-8':''">
        <template v-if="form.config_type === 1">
          <Ways v-model="form.config_ways[0]" />
        </template>
        <template v-else>
          <Ways class="mb-2" v-for="(d, i) in form.config_ways" :key="i" v-model="form.config_ways[i]" multi
            :checked="checked" @change="val => wayChange(val, i)" @remove="form.config_ways.splice(i, 1)" />
          <el-button size="small" :class="!form?.config_ways?.length?'px-[0] py-[0] mt-[-8px]':''" :disabled="checked[0] === 4 || checked.length === 4" @click="add" circle><i class="dk-iconfont icon-Plus" /></el-button>
        </template>
      </div>
      <el-form-item label="备注" class="mt-2">
        <el-input v-model="form.remark" type="textarea" placeholder="备注" :autoRows="{ minRow: 3 }" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.create" @click="create(formRef)">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive } from 'vue';
import api from '../api'
import { ElMessage } from 'element-plus'
import Ways from './Ways'
import {Plus} from '@element-plus/icons-vue'
const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})

// 表单处理
const formRef = ref()
const form = ref({})

// 打开弹窗
const open = async (id) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  form.value = {
    name: '',
    config_type: 1,
    status: 1,
    remark: '',
    config_ways: [{ config_way: 1,config_method:1 }]
  }
  loadings = reactive({})
  visible.value = true
  formRef?.value?.resetFields()
  // 编辑
  if (id) {
    const res = await api.detail({ sp_id: id })
    const { sp_id, name, config_type, status, remark, config_ways } = res.data
    form.value = { sp_id, name, config_type, status, remark, config_ways: (Array.isArray(config_ways) && config_ways.length > 0) ? config_ways : [{}] }
  }
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}

const checked = computed(() => form.value.config_ways.map(d => d.config_way))

const add = () => {
  const ways = [1, 5, 2, 3].filter(d => !form.value.config_ways.some(w => w.config_way === d))
  const timeWays = {
    1: 1,
    5: 2,
    2: 3,
    3: 4,
  }
  form.value.config_ways.push({ config_way: ways[0], percent: null, config_method: timeWays[ways[0]],settle_days:ways[0] === 1 ? 2 : null,settle_days_type:(ways[0]==2||ways[0]==3)?1:null })
}

const typeChange = (val) => {
  form.value.config_ways = [{ config_way: 1,config_method:1,settle_days:2}]
}

const wayChange = (val, i) => {
  if (val === 3 && i < 2) {
    form.value.config_ways = form.value.config_ways.slice(0, i + 1)
  }
}

// 提交
const create = async (formRef) => {
  const validator = await formRef.validate()
  if (!validator) return
  if (form.value.config_type === 2) {
    const hasInvalidPercent = form.value?.config_ways?.some(item =>
      item.percent === null || item.percent === undefined || item.percent === ''||item.percent === 0
    );
    if (hasInvalidPercent) {
      ElMessage.error('结算配置比例存在为空或为0的项，请检查后再提交!');
      return;
    }
  }
  loadings.create = true
  api[form.value.sp_id ? 'edit' : 'create'](form.value).then(res => {
    ElMessage.success('保存成功')
    emit('success')
    close()
  }).finally(() => {
    loadings.create = false
  })
}

defineExpose({ open })
</script>